package com.aw.guiguzi.module.common

import android.view.View
import android.widget.ImageView
import android.widget.TextView
import androidx.viewpager.widget.PagerAdapter
import androidx.viewpager.widget.ViewPager
import androidx.viewpager.widget.ViewPager.OnPageChangeListener
import com.aw.baselib.base.AwBaseBindingActivity
import com.aw.baselib.bean.CommonImgItemBean
import com.aw.baselib.constants.Extras
import com.aw.baselib.util.AwDataUtil
import com.aw.baselib.util.AwImgUtil
import com.aw.baselib.util.AwLog
import com.aw.baselib.util.download.AwFileDownloadUtil
import com.aw.baselib.util.download.DownloadResBean
import com.aw.guiguzi.R
import com.aw.guiguzi.databinding.ActivityImageBrowseBinding
import com.aw.guiguzi.widgets.ViewPagerFixed
import com.liulishuo.filedownloader.BaseDownloadTask
import com.liulishuo.filedownloader.FileDownloadListener
import java.io.File

/**
 * @ClassName: ImageBrowseActivity
 * @Description: 图片预览操作
 * @author: Sunhao
 * @date: 2020/5/13
 * @Copyright: 2020 www.baoneng.com Inc. All rights reserved. 注意：本内容仅限于宝能汽车公司内部传阅，禁止外泄以及用于其他的商业目
 */
class CommonImgActivity : AwBaseBindingActivity<ActivityImageBrowseBinding?>() {

    //图片数据
    private var imgList: List<CommonImgItemBean> = emptyList()

    //图片View集合
    private val mPicViews = ArrayList<View>()
    private var size = 0
    private var index = 0
    override fun getViewBinding(): ActivityImageBrowseBinding {
        return ActivityImageBrowseBinding.inflate(layoutInflater)
    }

    override fun initView() {
        try {
            imgList = intent.getParcelableArrayListExtra(Extras.params)!!
            index = intent.getIntExtra(Extras.params_int, 0)
            if (imgList != null && imgList.size > 0) {
                size = imgList.size
                for (imgItem in imgList) {
                    createPhotoView(imgItem)
                }
                val adapter = ImgBrowsePageAdapter(mPicViews)
                binding?.viewPagerImgBrowse?.adapter = adapter
                binding?.viewPagerImgBrowse?.currentItem = index
                setText(binding?.tvNum, (index + 1).toString() + "/" + size)
            }
        } catch (e: Exception) {
            e.printStackTrace()
        }
    }

    override fun initData() {
        super.initData()
        val title = intent.getStringExtra(Extras.title)
        setToolbar(if (AwDataUtil.isEmpty(title)) "图片浏览" else title, null)
    }

    override fun initListener() {
        super.initListener()
        binding?.viewPagerImgBrowse!!.setOnPageChangeListener(object : OnPageChangeListener {
            override fun onPageScrolled(
                position: Int,
                positionOffset: Float,
                positionOffsetPixels: Int
            ) {
            }

            override fun onPageSelected(position: Int) {
                setText(binding?.tvNum, (position + 1).toString() + "/" + size)
            }

            override fun onPageScrollStateChanged(state: Int) {}
        })
    }

    private fun createPhotoView(itemBean: CommonImgItemBean) {
        AwLog.d("createPhotoView, itemBean: $itemBean")
        try {
//            PhotoView img = new PhotoView(this);
            val view = layoutInflater.inflate(R.layout.view_img_item, null)
            val tv_desc = view.findViewById<TextView>(R.id.tv_desc)
            val img = view.findViewById<ImageView>(R.id.iv_img)
            AwImgUtil.setImg(
                mActivity,
                img,
                if (AwDataUtil.isEmpty(itemBean.imgPath)) itemBean.resId else itemBean.imgPath
            )
            img.setOnLongClickListener { v: View? ->
                showDialogCustomLeftAndRight(
                    "确定要保存到本地吗？",
                    "取消",
                    "确定",
                    { v1: View? -> dismissDialog() }) { v12: View? ->
                    if (!AwDataUtil.isEmpty(itemBean.imgPath) && itemBean.imgPath.startsWith("http")) {
                        downloadFile(itemBean.imgPath)
                    } else {
                        showMsg("文件地址不支持保存")
                    }
                }
                true
            }
            tv_desc.text = itemBean.describe
            mPicViews.add(view)
        } catch (e: Exception) {
            e.printStackTrace()
        }
    }

    internal inner class ImgBrowsePageAdapter(private val listViews: ArrayList<View>?) :
        PagerAdapter() {
        override fun getCount(): Int {
            return listViews?.size ?: 0
        }

        override fun getItemPosition(`object`: Any): Int {
            return POSITION_NONE
        }

        override fun destroyItem(arg0: View, arg1: Int, arg2: Any) {
            (arg0 as ViewPagerFixed).removeView(listViews!![arg1 % listViews.size])
        }

        override fun finishUpdate(arg0: View) {}
        override fun instantiateItem(arg0: View, arg1: Int): Any {
            try {
                (arg0 as ViewPagerFixed).addView(listViews!![arg1 % listViews.size], 0)
            } catch (e: IllegalArgumentException) {
            } catch (e: IndexOutOfBoundsException) {
            }
            return listViews!![arg1 % listViews.size]
        }

        override fun isViewFromObject(arg0: View, arg1: Any): Boolean {
            return arg0 == arg1
        }
    }

    private fun downloadFile(filePath: String) {
        val downloadResBeanList: MutableList<DownloadResBean> = ArrayList()
        val downloadResBean = DownloadResBean()
        downloadResBean.fileName = System.currentTimeMillis().toString() + ".png"
        downloadResBean.url = filePath
        val file = File(downloadResBean.path)
        if (file.exists()) {
            file.delete()
        }
        downloadResBeanList.add(downloadResBean)
        AwFileDownloadUtil.startDownload(
            downloadResBeanList,
            true,
            object : FileDownloadListener() {
                override fun pending(task: BaseDownloadTask, soFarBytes: Int, totalBytes: Int) {
                    AwLog.d("Main downloadFile pending....")
                    showLoadingDialog()
                }

                override fun progress(task: BaseDownloadTask, soFarBytes: Int, totalBytes: Int) {
                    AwLog.d("Main downloadFile progress....")
                }

                override fun completed(task: BaseDownloadTask) {
                    AwLog.d("Main downloadFile completed....")
                    showMsg("文件保存成功")
                    dismissLoadingDialog()
                }

                override fun paused(task: BaseDownloadTask, soFarBytes: Int, totalBytes: Int) {
                    AwLog.d("Main downloadFile paused....")
                }

                override fun error(task: BaseDownloadTask, e: Throwable) {
                    AwLog.d("Main downloadFile error....")
                    showMsg("文件保存出错")
                    dismissLoadingDialog()
                }

                override fun warn(task: BaseDownloadTask) {
                    AwLog.d("Main downloadFile warn....")
                }
            })
    }

    companion object {
        const val BROWSE_IMG_LIST = "browseImgList"
    }
}